import Entity from './Entity';
import LanguageMng from "../Managers/LanguageMng";
import GameLogicUtilTs from "../Utils/GameLogicUtilTs";

export default class Avatar extends Entity {

    //状态 0=掉线 1=在线 2=离开
    a_state = 0;
    //状态 0=未准备 1=已准备 2=游戏中 3=已提交 4=已Drop投降 5=被淘汰
    b_state = 0;
    //游戏ID
    id = 0;
    //头像
    img = '';
    //名字
    name = '';
    //性别
    gender = 0;
    //座位序列
    seat_no = -1;
    //等级
    level = 0;
    //金币
    coin = 0;
    //手牌
    cards = [];
    //客户端使用的手牌
    cardObjs = [];
    //客户端恢复出来的，成组的手牌
    s_cards_objs = [];
    //服务端发来的，恢复用的手牌牌组
    s_cards = []
    //客户端使用的局内分数(本局总分)
    score = 0;
    //face bg with only one color,generated by client
    face_bg = 0

    setSCardsObjs(sCardsObjs){
        this.s_cards_objs = sCardsObjs
    }

    setCards(cards){
        this.cards = cards
    }

    setSCards(scards){
        this.s_cards = scards
    }

    grabCard(card){
        if(!this.cards){
            cc.error("No avatar.cards array!")
            return
        }
        this.cards.push(card)
        cc.logfl("玩家保存手牌：",card,this.cards)
    }

    dropCard(card){
        if(!this.cards){
            cc.error("No avatar.cards array!")
            return
        }
        let idx = this.cards.indexOf(card)
        if(idx < 0){
            cc.error("No card ",card," in avatar.cards!")
            return
        }
        this.cards.splice(idx,1)
        cc.logfl("玩家丢弃手牌：",card,this.cards)
    }


    en_class() {
        return 'Avatar';
    }

    onDestroy() {
        super.onDestroy()
        cc.find("Canvas").emit("user_destroy",this.id)
    }

    initUser(gameMgr){
        this.gameMgr = gameMgr
        // cc.find("Canvas").emit("msgwatcher_add",function () {
        //     if(cc.gg.dataMgr.room){
        //         this.score = cc.gg.dataMgr.room.getAvatarOriginScore()
        //         cc.log("Avatar的score初始化为： ",this.score)
        //         return true
        //     }
        //     return false
        // }.bind(this))
        this.score = cc.gg.dataMgr.room.getTotalScore(this.id)
        if(this.uid !== cc.gg.dataMgr.getPlayerId()){

            this.face_bg = parseInt(Math.random()*1000000)
            cc.log("otherseat的头像背景颜色为：",this.face_bg)
        }



        this.onModifyEvent('a_state', (state) => this.onAStateChanged(state));
        this.onModifyEvent('b_state', (b_state) => this.onBStateChanged(b_state));
        this.onModifyEvent('coin', (coin) => this.onCoinChanged(coin));
        this.onModifyEvent('cards', (f_id) => this.onCardsChanged(f_id));
        this.onTriggerEvent('start', (data) => this.onGameStart(data));
        this.onTriggerEvent('grab', (data) => this.onUserGrab(data));
    }

    onUserGrab(data){
        cc.log("User收到grab消息！",data)
        let from = data[0]
        let poker = data[1]
        poker = cc.gg.dataMgr.convToClientPokerValue(poker)

        let pokerObj = null
        if(from !== cc.gg.enumConfig.GrabFrom.DISCARDS){
            pokerObj = {id:cc.gg.dataMgr.generateNewPokerId(),poker:poker}
            cc.find("Canvas").emit("game_self_grap",this.id,from,pokerObj)
        }

        if(this.id === cc.gg.dataMgr.getPlayerUser().id){
            this.grabCard(poker)
        }
    }

    onGameStart(data){
        cc.log("entiry user:  room start",data)
        cc.gg.gameDataUtil.gameStarted = true
        cc.gg.gameDataUtil.receiveFinish = false
        if(!cc.gg.dataMgr.room.round){
            cc.find("Canvas").emit("game_init_user_score")
        }

        let users = data[0]     //pick poker to compare to decide who is the first graber
        if(users){
            cc.gg.dataMgr.room.comps = users
            for(let i=0;i<users.length;i++){
                let obj = users[i]
                obj.card = cc.gg.dataMgr.convToClientPokerValue(obj.card)
            }
        }
        let userCards = data[1]
        let botCardArray = data[2]
        let joker = cc.gg.dataMgr.convToClientPokerValue(data[3])

        cc.gg.dataMgr.room.joker = joker
        cc.gg.dataMgr.room.joker_obj = cc.gg.dataMgr.convToClientPokerObj(joker)
        // this.cards = userCards
        this.setCards(userCards)
        cc.log("服务端传来的牌：",userCards)
        if(!userCards){
            this.cardObjs = null
        }else {
            this.cardObjs = cc.gg.dataMgr.convertToClientPokerObj(userCards)
        }

        cc.gg.dataMgr.room.c_open = botCardArray
        cc.gg.dataMgr.room.c_open_objs = cc.gg.dataMgr.convertToClientPokerObj(botCardArray)


        cc.gg.tpgMgr.changeOptionState(cc.gg.enumConfig.OptionState.DISPATCHING)
        cc.gg.tpgMgr._animDispatching = true
        cc.log("start:users:",users)
        // if(users) cc.gg.tpgMgr.updateSeatSequence(users)

        if(!users){
            cc.log("start:直接开始发牌")
            this.startStartDispathing()
        }else {
            cc.log("start:round是0，比点显示")
            cc.gg.tpgMgr.showPokerStack(false)

            let delayTime = cc.gg.tpgMgr.showCompare(users)
            let self = this
            GameLogicUtilTs.needStopDispatching = false
            setTimeout(function () {
                if(GameLogicUtilTs.needStopDispatching) {
                    cc.warn("刚刚重连了，停止延迟动画")
                    return
                }
                cc.gg.tpgMgr.showPokerStack(true)
            }.bind(this),(delayTime)*1000)
            setTimeout(function () {
                if(GameLogicUtilTs.needStopDispatching)  {
                    cc.warn("刚刚重连了，停止延迟动画")
                    return
                }
                self.startStartDispathing()
            }.bind(this),(delayTime+1)*1000)
        }


        // if(this.b_state === cc.gg.enumConfig.ReadyState.ELIMINATED){
        //     cc.gg.tpgMgr.showHandPokerMask(true)
        // }
    }

    startStartDispathing(){
        if(!cc.gg.dataMgr.room){
            console.log("房间room已经销毁，停止发牌startStartDispathing方法")
            return
        }
        let bottomCard = cc.gg.dataMgr.room.c_open[0]
        cc.gg.tpgMgr.onStartGame(this.cardObjs,cc.gg.dataMgr.room.joker,bottomCard)
        cc.find("Canvas/UIManager").emit("ui_hide_score")
        cc.find("Canvas").emit("close_windows")
        cc.find("Canvas").emit("game_count_down_stop")
    }

    onAStateChanged(a_state){
        this.a_state = a_state
        cc.logfl("user on a state changed ",a_state)
        if(a_state === 0){
            cc.find("Canvas").emit("user_offline",this.id)
        }else if(a_state === 1){
            cc.find("Canvas").emit("user_online",this.id)
        }else if(a_state === 2){
            cc.find("Canvas").emit("user_leave",this.id)
        }
    }

    onBStateChanged(b_state){
        this.b_state = b_state
        cc.logfl("user on b state changed ",b_state)
        cc.find("Canvas/UIManager").emit("game_user_ready_change",this.id,b_state)
    }

    onCardsChanged(cards){
        this.cards = cards
        cc.logfl("user onCardsChanged ",cards)
    }

    onCoinChanged(coin){
        this.coin = coin
        cc.logfl("user onCoinChanged ",coin)
        if(this.a_state !== 2) cc.find("Canvas/UIManager").emit("user_coin_changed",this.id,coin)
    }

    /**
     * 请求准备，若已准备则取消准备
     */
    ready() {
        if (this.b_state === 1 || this.b_state === 2) return;
        cc.log("发送ready!")
        this.trigger('ready');
    }

    /**
     * 请求离考房间
     */
    async leave() {
        GameLogicUtilTs.wantQuitRoom = true
        let forceQuit = cc.gg.dataMgr.room ? cc.gg.dataMgr.room.isForceQuit() : false
        if(!this.trigger('leave2',[forceQuit])){
            cc.log("ws已经断开，用户想退出，直接退出到大厅")
            cc.gg.gameDataUtil.goToLobby(true)
        }
    }

    /**
     * 请求抓牌
     * @param from 1=明牌堆 2=剩余牌堆
     */
    async grab(from) {
        if (this.b_state != 2) return
        cc.logws("Send grab from " ,from)

        // let code =
        return await this.trigger('grab', [from]);
    }

    /**
     * 请求弃牌
     * @param card
     */
    async discard(card) {
        if (this.b_state != 2) return;
        cc.logws("user ",this.id," send discard ",card)

        // this.dropCard(card)
        return await this.trigger('discard', [card]);
    }

    /**
     * 请求提交牌组
     * @param cards 二维数组
     */
    commit(cards) {
        if (this.b_state === 3) return;
        this.trigger('commit', [cards]);
    }


    /**
     * 直接提交牌组
     * @param cards 二维数组
     */
    finish(cards,card){
        if (this.b_state === 3) return;

        card = cc.gg.dataMgr.convToServerPokerValue(card)
        cc.logws("client.finish:",JSON.stringify([cards,card]))
        this.trigger('finish', [cards,card]);
    }

    /**
     * 同步手牌
     * @param cards 二维数组
     */
    async sync(cards){
        if (this.b_state === 3 || this.b_state === 0) return;

        cc.logfl("同步牌组信息",cards)
        cards = cc.gg.dataMgr.convToServerPokervalueArray(cards)
        cc.logws("client.sync:",cards)

        this.setSCards(cards)
        // let code = await ;
        this.trigger('sync', [cards]).then(code => {
            if (code == 5) {
                cc.error("提交的牌组与手牌不符")
                return
            }
        })
    }

    drop(){
        if (this.b_state === 3 || this.b_state === 0){
            cc.warn("当前阶段不能drop，客户端逻辑错误！")
            return
        }

        this.trigger('drop');
    }
}